package org.dizena.quartz.adapter.config;

import jakarta.annotation.Resource;
import org.dizena.quartz.adapter.listener.SimpleJobListener;
import org.dizena.quartz.adapter.listener.SimpleSchedulerListener;
import org.dizena.quartz.adapter.listener.SimpleTriggerListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.matchers.EverythingMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfig {

    @Resource
    private SimpleSchedulerListener simpleSchedulerListener;

    @Resource
    private SimpleJobListener simpleJobListener;

    @Resource
    private SimpleTriggerListener simpleTriggerListener;


    @Bean(name = "scheduler")
    public Scheduler scheduler(@Autowired SchedulerFactoryBean factory) throws SchedulerException {
        Scheduler scheduler = factory.getScheduler();
        //全局添加监听器
        //添加SchedulerListener监听器
        scheduler.getListenerManager().addSchedulerListener(simpleSchedulerListener);

        // 添加JobListener, 支持带条件匹配监听器 ,KeyMatcher.keyEquals(JobKey.jobKey("test", "dev"))
        scheduler.getListenerManager().addJobListener(simpleJobListener);

        // 添加triggerListener，设置全局监听
        scheduler.getListenerManager().addTriggerListener(simpleTriggerListener, EverythingMatcher.allTriggers());

        return scheduler;
    }

}
